package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.job.vo.IotMsgNotifyData;
import com.zzyl.nursing.job.vo.IotMsgService;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.vo.DeviceDataGraphVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.zzyl.common.constant.CacheConstants.IOT_DEVICE_LAST_DATA;

/**
 * 设备数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-15
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper,DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备上报数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备上报数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备上报数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData)?1:0;
    }

    /**
     * 修改设备上报数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData)?1:0;
    }

    /**
     * 批量删除设备上报数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备上报数据
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id)?1:0;
    }

    /**
     * 批量新增设备上报数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    @Transactional
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        // 1、根据IOT设备ID查询设备信息
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = this.deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId));

        // 2、判断该设备是否存在
        if(ObjectUtil.isEmpty(device)){
            log.error("设备不存在，IOT设备ID：{}", deviceId);
            return;
        }

        // 3、获取设备上报数据，保存到数据库（一个设备可以有多个services）
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        for (IotMsgService service : services) {
            Map<String, Object> properties = service.getProperties();
            if(ObjectUtil.isEmpty(properties)){
                continue;
            }

            //处理上报时间日期
            LocalDateTime eventTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            List<DeviceData> deviceDataList = new ArrayList<>(properties.size());
            properties.forEach((key,value) -> {
                DeviceData deviceData = DeviceData.builder()
                        .iotId(deviceId)
                        .functionId(key)
                        .accessLocation(device.getRemark())
                        .dataValue(value.toString())
                        .alarmTime(alarmTime)
                        .build();
                BeanUtil.copyProperties(device,deviceData,"id","createBy","createTime","updateBy","updateTime");
                // BeanUtil.copyProperties(device,deviceData);
                deviceDataList.add(deviceData);
            });

            // 批量保存
            this.saveBatch(deviceDataList);

            // 将该设备最新上报数据 保存至 Redis（供后续查询使用）
            redisTemplate.opsForHash().put(IOT_DEVICE_LAST_DATA,deviceId,deviceDataList);
        }
    }

}
